package cn.yunbamboos.rest.service.converter;

import cn.hutool.core.util.ObjUtil;
import cn.yunbamboos.exception.AppException;
import cn.yunbamboos.rest.service.IRestService;
import cn.yunbamboos.rest.service.ISession;
import cn.yunbamboos.rest.service.dto.in.BaseInDTO;
import cn.yunbamboos.rest.service.dto.in.FileInDTO;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;

import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RequestConverterFileInDTO extends RequestConverterInDTO {

    private static final Logger logger = LoggerFactory.getLogger(RequestConverterFileInDTO.class);

    public RequestConverterFileInDTO() {
        super(MediaType.MULTIPART_FORM_DATA);
    }

    @Override
    public BaseInDTO converter() {
        ISession session = sessionContainer.getSession();
        if (ObjUtil.isNull(session)) {
            throw AppException.c("session is null");
        }
        IRestService service = session.getService();

        // 读取请求内容
        HttpServletRequest request = session.getRequest();
        BaseInDTO in = service.createInDTO().create(new JSONObject());
        if (in instanceof FileInDTO file) {
            file.decodeFile(request);
            return in;
        }

//        StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
//        if (resolver.isMultipart(httpServletRequest)) {
//            MultipartHttpServletRequest request = resolver.resolveMultipart(httpServletRequest);
//            BaseInDTO in = service.createInDTO().create(new JSONObject());
//            if (in instanceof FileInDTO file) {
//                file.decodeFile(request);
//                return file;
//            }
//            throw AppException.c("{} need to extends FileInDTO", service.in().getSimpleName());
//        }
        throw AppException.c("Request Converter DTO is unrealized");
    }
}
